// BlogFileIO.cpp: implementation of the CBlogFileIO class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "SinaBlog.h"
#include "BlogFileIO.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CBlogFileIO::CBlogFileIO(CString strBlogFilePath)
{
	m_oFile.Open(strBlogFilePath, CFile::modeCreate|CFile::modeNoTruncate|CFile::modeReadWrite|CFile::shareDenyWrite);
}

CBlogFileIO::~CBlogFileIO()
{
	m_oFile.Close();
}

void CBlogFileIO::WriteURL(CString strBlogURL, BOOL bToday)
{
	BOOL bWrite = TRUE;
	if(bToday)
	{
		m_oFile.SeekToBegin();
		CString strLine;
		m_oFile.ReadString(strLine);
		if(strLine.Left(3) == "VER")
		{
			m_oFile.ReadString(strLine);
			if(strLine.Left(3) == "URL")
			{
				bWrite = FALSE;
			}
		}
		else if(strLine.Left(3) == "URL")
		{
			bWrite = FALSE;
		}
	}

	if(bWrite)
	{
		m_oFile.SeekToEnd();
		m_oFile.WriteString(CString("URL: ") + strBlogURL + CString("\n"));
		m_oFile.Flush();
	}
}

void CBlogFileIO::WriteVER(CString strVersion, BOOL bToday)
{
	BOOL bWrite = TRUE;
	if(bToday)
	{
		m_oFile.SeekToBegin();
		CString strLine;
		m_oFile.ReadString(strLine);
		if(strLine.Left(3) == "VER" || strLine.Left(3) == "URL")
		{
			bWrite = FALSE;
		}
	}
	
	if(bWrite)
	{
		m_oFile.SetLength(0);
		m_oFile.Flush();
		m_oFile.WriteString(CString("VER: ") + strVersion + CString("\n"));
	}
}

void CBlogFileIO::WriteTitle(CString strTitle, BOOL bToday)
{
	BOOL bWrite = TRUE;
	if(bToday)
	{
		m_oFile.SeekToBegin();
		CString strLine;
		m_oFile.ReadString(strLine);
		if(strLine.Left(3) == "VER")
		{
			m_oFile.ReadString(strLine);
			if(strLine.Left(3) == "URL")
			{
				m_oFile.ReadString(strLine);
				if(strLine.Left(5) == "TITLE")
				{
					bWrite = FALSE;
				}
			}
		}
		else if(strLine.Left(3) == "URL")
		{
			m_oFile.ReadString(strLine);
			if(strLine.Left(5) == "TITLE")
			{
				bWrite = FALSE;
			}
		}
	}
	
	if(bWrite)
	{
		m_oFile.SeekToEnd();
		m_oFile.WriteString(CString("TITLE: ") + strTitle + CString("\n"));
		m_oFile.Flush();
	}
}

void CBlogFileIO::WriteBlogLine(CString strBlogLine)
{
	m_oFile.SeekToEnd();
	m_oFile.WriteString(strBlogLine + CString("\n"));
}
